package com.agh.portal.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.agh.portal.domain.AghGroup;
import com.agh.portal.domain.Post;
import com.agh.portal.domain.Reply;
import com.agh.portal.domain.Student;
import com.agh.portal.service.DataService;
import com.agh.portal.service.SecurityUtils;

@RequestMapping("/posts")
@Controller
@RooWebScaffold(path = "posts", formBackingObject = Post.class)
@RooWebFinder
public class PostController {
	
	@Autowired
	SecurityUtils secUtils;
	
    @RequestMapping(params = {"form", "groupId"}, produces = "text/html")
    public String createForm(Model uiModel, @RequestParam(value = "groupId", required = false) Long groupId) {
    	 uiModel.addAttribute("aghGroup", AghGroup.findAghGroup(groupId));
        populateEditForm(uiModel, new Post());
        return "posts/create";
    }
	
    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Post post, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, post);
            return "posts/create";
        }
        uiModel.asMap().clear();
        post.setPostDate(new Date());
        post.persist();
        return "redirect:/posts/" + encodeUrlPathSegment(post.getId().toString(), httpServletRequest);
    }
	
    @RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        Post p = Post.findPost(id);
        uiModel.addAttribute("post", p);
        uiModel.addAttribute("replies", DataService.sortRepliesByDate(p.getReplies()));
        uiModel.addAttribute("itemId", id);
        return "posts/show";
    }
    
    void populateEditForm(Model uiModel, Post post) {
        uiModel.addAttribute("post", post);
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("student", secUtils.getLoggedStudent());
    }
	
}
